<?php

/**
 * 系统通知
 * File Name：MessageModel.php
 * File Encoding：UTF-8
 * File New Time：2014-8-19 15:41:26
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class MessageModel extends BaseModel {

    //通知类型
    const system = 0; //系统通知
    const sns = 1; //私信
    const goods = 2; //商品相关，如 审核通知
    const friends = 3; //好友相关，申请好友
    const watch = 4; //关注
    const comments = 5; //评论
    const redeem = 6; //积分兑换
    const report = 7; //举报

    public function tableName() {
        return '{{message}}';
    }

    public function rules() {
        return array(
            array('userid,typeid,is_read,title,senduid,sendname,extend_params,datetime', 'safe'),
        );
    }

    //数据保存前操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->datetime = time();
        }
        return true;
    }

    //数据保存后回调
    protected function afterSave() {
        if (isset($this->userid) && $this->userid) {
            $this->isNews($this->userid, false);
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 发送通知(经过redis中转)
     * @param type $uid 接收用户UID
     * @param type $sendUser false为系统发送，产生通知的用户信息，字符串是用户名，数字是UID，数组是必须包含 uid,username
     * @param type $typeId 通知类型
     * @param array $extendParams 通知参数
     * @return boolean
     */
    public function notice($uid, $sendUser, $typeId, $extendParams = array()) {
        //开发环境下直接走数据库形式
        if (defined('YII_DEBUG') && YII_DEBUG) {
            return $this->sendNotice($uid, $sendUser, $typeId, $extendParams);
        }
        $data = array(
            'uid' => $uid,
            'sendUser' => $sendUser,
            'typeId' => $typeId,
            'extendParams' => $extendParams,
        );
        RedisCluster::getInstance()->push('snsMessage', $data);
        return true;
    }

    /**
     * 发送一条系统通知
     * @param type $uid 接收用户UID
     * @param array $extendParams 通知参数，通知正文在content里
     * @return type
     */
    public function systemNotice($uid, $extendParams) {
        if (empty($extendParams)) {
            return false;
        }
        return $this->notice($uid, false, self::system, $extendParams);
    }

    /**
     * 发送通知(直接数据库方式)
     * @param type $uid 接收用户UID
     * @param type $sendUser 产生通知的用户信息，字符串是用户名，数字是UID，数组是必须包含 uid,username
     * @param type $typeId 通知类型
     * @param type $extendParams 通知参数
     * @return boolean
     */
    public function sendNotice($uid, $sendUser, $typeId, $extendParams = array()) {
        if (empty($uid)) {
            return false;
        }
        if ($sendUser === false) {
            $sendUser = array(
                'uid' => 0,
                'username' => '系统通知',
            );
        }
        if (!is_array($sendUser)) {
            $userInfo = MembersModel::model()->getUserInfo($sendUser);
            $sendUser = array(
                'uid' => $userInfo['uid'],
                'username' => $userInfo['username'],
            );
        }
        $post = array(
            'userid' => $uid,
            'typeid' => $typeId,
            'title' => $extendParams['title'] ? $extendParams['title'] : '您有一条新的通知！',
            'senduid' => $sendUser['uid'],
            'sendname' => $sendUser['username'],
            'extend_params' => serialize($extendParams),
        );
        $this->attributes = $post;
        if ($this->validate()) {
            //检查接收通知的用户最新一条是不是同一个用户产生的，如果是，不添加新的，直接进行更新
            //$isNewNotice = self::goods == $typeId ? false : $this->find($this->where(array('userid' => $post['userid'], 'senduid' => $post['senduid'], 'typeid' => $post['typeid'], 'order' => 'nid desc')));
            if (false) {
                unset($post['userid']);
                $isNewNotice->attributes = $post;
                $isNewNotice->datetime = time();
                $isNewNotice->is_read = 0;
                return $isNewNotice->save() ? true : false;
            } else {
                unset($this->nid);
                $this->setIsNewRecord(true);
                return $this->save();
            }
        } else {
            return false;
        }
    }

    /**
     * 发送一般通知(无类型)
     * @param int $uid
     * @param string $content
     * @param string $title
     */
    public function sendDefaultNotice($uid, $content, $title = '') {
        $extendParams = array('content' => $content, 'title' => $title);
        return $this->sendNotice($uid, false, self::system, $extendParams);
    }

    /**
     * 设置通知状态为已读
     * @param type $nid 可以是数组，可以是单条通知id
     * @return boolean
     */
    public function noticeRead($nid, $uid = 0) {
        if (empty($nid)) {
            return false;
        }
        $where = array();
        if (is_array($nid)) {
            $where['nid'] = array('IN', $nid);
        } else {
            $where['nid'] = $nid;
        }
        $status = $this->updateAll(array('is_read' => 1), $this->where($where));
        $this->isNews($uid, false);
        return $status;
    }

    /**
     * 是否有新通知，有，返回未读消息数。
     * @param type $uid 用户UID
     * @return int
     */
    public function isNews($uid, $isCache = true) {
        if (empty($uid)) {
            return 0;
        }
        $key = "MessageModel_isNews_{$uid}";
        if (!$isCache) {
            Yii::app()->cache->delete($key);
            return true;
        }
        $isNews = Yii::app()->cache->get($key);
        if (is_bool($isNews) && $isNews == false) {
            $isNews = $this->getNoticeNoReadCount($uid);
            Yii::app()->cache->set($key, $isNews, 300);
        }
        return $isNews;
    }

    /**
     * 获取用户未读取通知数
     * @param type $userid
     * @return int
     */
    public function getNoticeNoReadCount($userid) {
        if (empty($userid)) {
            return 0;
        }
        return $this->count($this->where(array('userid' => $userid, 'is_read' => 0)));
    }

    /**
     * 删除用户指定的通知
     * @param type $userid 用户UID
     * @param type $nid 通知ID
     * @return boolean
     */
    public function noticeDel($userid, $nid) {
        if (empty($userid) || empty($nid)) {
            return false;
        }
        return $this->deleteAll($this->where(array('userid' => $userid, 'nid' => $nid)));
    }

    /**
     * 删除用户全部已读消息消息
     * @param type $userid 用户ID
     * @return boolean
     */
    public function delReadAll($userid) {
        if (empty($userid)) {
            return false;
        }
        return $this->deleteAll($this->where(array('userid' => $userid, 'is_read' => 1)));
    }

}
